﻿using Microsoft.EntityFrameworkCore;
using Sgr.Domain.Entities.Auditing;
using Sgr.EntityFrameworkCore;
using Sgr.Generator;
using Sgr.Domain.Repositories;
using Sgr.UPMS.Domain.Departments;
using Sgr.Exceptions;

namespace Sgr.UPMS.Infrastructure.Repositories
{
    /// <summary>
    /// 部门仓储实现
    /// </summary>
    /// <remarks>
    /// 实现了树形结构的部门管理，支持：
    /// - 部门树形结构的增删改查
    /// - 部门层级关系维护
    /// - 部门状态管理
    /// </remarks>
    public class DepartmentRepository<TDbContext> : EfCoreTreeNodeBaseRepositoryOfTEntityAndTPrimaryKey<TDbContext, Department, long>, IDepartmentRepository
        where TDbContext : UnitOfWorkDbContext
    {
        private readonly ISegmentNumIdGenerator _numberIdGenerator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContextProvider"></param>
        /// <param name="auditedOperator">审计操作者</param>
        /// <param name="numberIdGenerator">数字ID生成器</param>
        /// <exception cref="BusinessException">参数为空时抛出异常</exception>
        public DepartmentRepository(
            IDbContextProvider<TDbContext> dbContextProvider,
            IAuditedOperator auditedOperator,
            ISegmentNumIdGenerator numberIdGenerator)
            : base(dbContextProvider, auditedOperator)
        {
            _numberIdGenerator = numberIdGenerator ?? throw new ArgumentNullException(nameof(numberIdGenerator));
        }

        /// <summary>
        /// 检查同级部门下是否存在相同名称
        /// </summary>
        /// <param name="orgId">组织标识</param>
        /// <param name="name">部门名称</param>
        /// <param name="parentId">父级部门ID</param>
        /// <param name="excludeId">需要排除的部门ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>是否存在</returns>
        public async Task<bool> IsNameExistsInSameLevelAsync(
            long orgId,
            string name,
            long parentId,
            long? excludeId = null,
            CancellationToken cancellationToken = default)
        {
            Check.StringNotNullOrEmpty(name, nameof(name));

            var query = await GetQueryableAsync(cancellationToken);
            query = query.AsNoTracking()
                .Where(x => x.OrgId == orgId && x.ParentId == parentId && x.Name == name);

            if (excludeId.HasValue)
            {
                query = query.Where(x => x.Id != excludeId.Value);
            }

            return await query.AnyAsync(cancellationToken);
        }

        /// <summary>
        /// 检查并设置主键Id
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        protected override async Task CheckAndSetIdAsync(Department entity, CancellationToken cancellationToken = default)
        {
            if (entity.Id == 0)
                entity.Id = await _numberIdGenerator.GetUniqueIdAsync(UpmsConstant.DEFAULT_SEGMENT_KEY, cancellationToken);
        }
    }
}